<template>
    <div class="preview-container">
        <div class="phone-content">
            <div class="phone-wrapper">
                <div class="phone-mockup">
                    <div class="phone-mockup-content">
                        <div class="status-bar">
                            <img src="https://image.lutongjiakao.com/system/354d97034af84a0a9817ad0191d879d8.png"
                                alt="">
                        </div>
                        <div class="header-content" :class="{ 'header-selected': isHeaderSelected }"
                            @click="selectHeader">
                            <div class="app-header">
                                <i class="iconfont-sys menu-btn">&#xe7dc;</i>
                                <h1 class="app-title">{{ headerConfig.title || '测试' }}</h1>
                                <i class="iconfont-sys menu-btn">&#xe839;</i>
                            </div>
                            <div class="hero-section">
                                <div class="hero-background" :class="{ 'has-bg-image': headerConfig.backgroundImage }"
                                    :style="headerBackgroundStyle">
                                    <div class="hero-content">
                                        <h2 v-if="!headerConfig.hideTitle" class="hero-title">
                                            {{ headerConfig.title || '测试' }}
                                        </h2>
                                        <p class="hero-subtitle">{{ headerConfig.description }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 表单内容区域 -->
                        <VueDraggable v-model="formComponents" :animation="150" group="people" ghostClass="ghost"
                            class="form-content" :filter="'.el-scrollbar'" :preventOnFilter="false" @add="onAdd">
                            <div class="form-components" v-for="(component, index) in formComponents"
                                :key="component.id">
                                <i class="iconfont-sys delete-x" @click.stop="deleteComponent(index)">&#xe665;</i>
                                <div class="form-component" :class="{ active: selectedComponentIndex === index }"
                                    @click="selectFormComponent(index)">
                                    <!-- <div class="component-preview"> -->
                                    <component-preview :component="component" />
                                    <!-- </div> -->
                                </div>
                            </div>
                        </VueDraggable>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import ComponentPreview from './componentPreview.vue'

const emit = defineEmits<{
    'component-selected': [component: any]
    'header-selected': []
}>()

interface FormComponent {
    id: string
    type: string
    label: string
    icon: string
    config?: any
}

const formComponents = ref<FormComponent[]>([])
const selectedComponentIndex = ref(-1)
const isHeaderSelected = ref(true) // 默认选中 header

// Header 配置数据
const headerConfig = ref({
    title: '测试',
    description: '建议在此输入机构的介绍内容或表单的填写引导',
    backgroundImage: '',
    hideTitle: false
})

// 计算背景样式
const headerBackgroundStyle = computed(() => {
    if (headerConfig.value.backgroundImage) {
        return {
            backgroundImage: `url(${headerConfig.value.backgroundImage})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat'
        }
    }
    return {}
})

const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`

// 选择 Header
const selectHeader = () => {
    isHeaderSelected.value = true
    selectedComponentIndex.value = -1
    emit('header-selected')
}

// 选择表单组件
const selectFormComponent = (index: number) => {
    isHeaderSelected.value = false
    selectedComponentIndex.value = index
    // 触发组件选择事件
    emit('component-selected', formComponents.value[index])
}

// 更新 Header 配置
const updateHeaderConfig = (config: any) => {
    Object.assign(headerConfig.value, config)
}

// 获取 Header 配置
const getHeaderConfig = () => {
    return headerConfig.value
}

// 删除组件
const deleteComponent = (index: number) => {
    formComponents.value.splice(index, 1)

    const remaining = formComponents.value.length
    if (remaining > 0) {
        // 选中相邻的一项（删除后当前位置或最后一项）
        const nextIndex = Math.min(index, remaining - 1)
        isHeaderSelected.value = false
        selectedComponentIndex.value = nextIndex
        emit('component-selected', formComponents.value[nextIndex])
    } else {
        // 没有组件时回到表头配置
        selectedComponentIndex.value = -1
        isHeaderSelected.value = true
        emit('header-selected')
    }

    ElMessage.success('删除成功')
}

// 添加组件
const addComponent = (component: any) => {
    const withId = component && component.id ? component : { ...component, id: generateId() }
    formComponents.value.push(withId)
    isHeaderSelected.value = false
    selectedComponentIndex.value = formComponents.value.length - 1
    // 触发组件选择事件
    emit('component-selected', withId)
}

const onAdd = (evt: any) => {
    const newIndex = evt?.newIndex ?? -1
    if (newIndex < 0) return
    const dropped = formComponents.value[newIndex]
    if (dropped && !dropped.id) {
        dropped.id = generateId()
    }
    isHeaderSelected.value = false
    selectedComponentIndex.value = newIndex
    emit('component-selected', formComponents.value[newIndex])
}

// 首次加载时默认选中 header 并发出 header-selected 事件
onMounted(() => {
    isHeaderSelected.value = true
    selectedComponentIndex.value = -1
    emit('header-selected')
})

// 暴露方法给父组件调用
defineExpose({
    addComponent,
    updateHeaderConfig,
    getHeaderConfig,
    isHeaderSelected
})

</script>

<style lang="scss" scoped>
.preview-container {
    width: 100%;
    background: #f5f5f5;
    padding: 20px 0;
}

.phone-content {
    height: 100%;
    display: flex;
    justify-content: center;
    overflow-y: auto;
}

.phone-wrapper {
    height: 875px;
}

.phone-mockup {
    width: 375px;
    min-height: 100%;
    border-radius: 28px;
    padding: 16px;
    position: relative;
    background-color: #fff;
    box-sizing: border-box;
}

// 状态栏
.status-bar {
    position: relative;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // background: transparent;
    background: #f8f9fa;
    border-radius: 16px 16px 0 0;
    color: #000;
    font-size: 14px;
    font-weight: 600;

    img {
        width: 100%;
        height: 100%;
    }
}

.status-left {
    .time {
        font-size: 16px;
        font-weight: 600;
    }
}

.status-right {
    display: flex;
    align-items: center;
    gap: 4px;
}

.signal-bars {
    display: flex;
    align-items: end;
    gap: 2px;
    margin-right: 4px;

    .bar {
        width: 3px;
        background: #000;
        border-radius: 1px;

        &:nth-child(1) {
            height: 4px;
        }

        &:nth-child(2) {
            height: 6px;
        }

        &:nth-child(3) {
            height: 8px;
        }

        &:nth-child(4) {
            height: 10px;
        }
    }
}

.wifi-icon,
.battery-icon {
    font-size: 12px;
}

// 应用标题栏
.app-header {
    position: relative;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 10px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
}

.menu-btn {
    font-size: 20px;
    cursor: pointer;
    font-weight: 700;
    color: #333;
}

.app-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.header-content {
    margin-bottom: 10px;
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;
    border: 1px dashed transparent;

    &.header-selected {
        border: 1px dashed #1677ff;
    }

    &:hover {
        border: 1px dashed #1677ff;
    }
}

.hero-section {
    position: relative;
    z-index: 10;
    height: 200px;
    overflow: hidden;
}

.hero-background {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    background-image:
        radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
        radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
        radial-gradient(circle at 40% 80%, rgba(120, 219, 255, 0.3) 0%, transparent 50%);
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background-image 0.3s ease;

    &.has-bg-image {
        background: transparent;
        background-image: none;
    }
}

.hero-content {
    text-align: center;
    color: #333;
    z-index: 2;
}

.hero-title {
    font-size: 24px;
    font-weight: 700;
    margin: 0 0 8px 0;
    color: #333;
}

.hero-subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
    line-height: 1.4;
    max-width: 280px;
}

.phone-mockup-content {
    border: 1px solid #e5e6eb;
    border-radius: 16px;
    // overflow: hidden;
}

// 表单内容区域
.form-content {
    position: relative;
    z-index: 10;
    background: #fff;
    // border: 2px dashed transparent;
    transition: all 0.3s ease;
    min-height: 539px; // 设置固定高度，可根据实际需求调整
    display: flex;
    flex-direction: column;
    gap: 10px;
    border-radius: 0 0 16px 16px;
    padding-bottom: 20px;
    // &.drag-over {
    //     border-color: #1677ff;
    //     background: #f0f8ff;
    // }
}

// VueDraggable 容器样式
.draggable-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.form-components {
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;

    .form-component {
        border: 1px solid #fff;
        background: #fff;
        transition: all 0.2s ease;
        overflow: hidden;
        position: relative;

        &.active {
            border: 1px dashed #1677ff;
        }

        &:hover {
            border: 1px dashed #1677ff;
        }

        // 拖拽手柄
        .drag-handle {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            cursor: grab;
            opacity: 0;
            transition: all 0.2s ease;
            z-index: 10;

            span {
                font-size: 12px;
                color: #666;
                font-weight: bold;
                line-height: 1;
                transform: rotate(90deg);
            }

            &:active {
                cursor: grabbing;
            }
        }

        &:hover .drag-handle {
            opacity: 1;
        }
    }

    // 删除按钮显示隐藏控制
    .delete-x {
        position: absolute;
        top: -9px;
        right: -9px;
        font-size: 18px;
        z-index: 20;
        text-align: center;
        opacity: 0;
        pointer-events: none;
        cursor: pointer;
        color: #aaaaaa;
    }

    &:hover .delete-x,
    .delete-x:focus {
        opacity: 1;
        pointer-events: auto;
    }
}

// VueDraggable 拖拽状态样式
.ghost {
    opacity: 0.5;
    background: #f0f8ff;
    border: 2px dashed #1677ff;
}

.chosen {
    transform: rotate(2deg);
    box-shadow: 0 4px 12px rgba(22, 119, 255, 0.2);
}

.drag {
    opacity: 0.8;
    transform: rotate(2deg);
}

.component-preview {
    padding: 15px;
}

// 响应式设计
@media (max-width: 768px) {
    .preview-container {
        padding: 10px;
    }

    .phone-mockup {
        width: 320px;
        height: 640px;
        border-radius: 30px;
        /* 注意此时高度固定为 640px 了，内容再多只显示滚动条 */
        max-height: 640px;
        min-height: unset;
    }
}
</style>